<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Model
{
	private	$CI;
	
	protected $maintable = 'usermain';
	protected $logintable = 'userlog';
	
	public function __construct()
	{
		$this->CI = get_instance();
	}
	
	
	/** Check if user exists
	 * @param : user nickname
	 * @return : true if user exists, false if not.
	 */
	public function existingUser( $inNickname )
	{
		$results = $this->db->select( 'nick' )
							->from( $this->maintable )
							->where ('nick', $inNickname )
							->get()
							->result();
		
		if ( empty( $results ) ) 
			return false;
		else
			return true;
	}
	
	/** Get user nickname
	 * @param : user uid
	 * @return : user nickname, or false if don't exists
	 */
	public function getUserNick( $inUid )
	{
		if( $inUid === FALSE )
			return false;	
	
		$results = $this->db->select( 'nick' )
							->from( $this->maintable )
							->where ('userid', $inUid )
							->get()
							->result();
		
		if ( empty( $results ) ) 
			return false;
		else
		{
			return $results[0]->nick;
		}
	}
	
	
	/** Get user uid
	 * @param : user nickname
	 * @return : user uid, or false if don't exists
	 */
	public function getUserId( $inNickname )
	{
		if( $inNickname === FALSE )
			return false;	
	
		$results = $this->db->select( 'userid' )
							->from( $this->maintable )
							->where ('nick', $inNickname )
							->get()
							->result();
		
		if ( empty( $results ) ) 
			return false;
		else
		{
			return $results[0]->userid;
		}
	}
	
	/** Check user login info
	 * @param : user id
	 * @param : user md5 pwd
	 * @return : true if login infos are correct
	 */
	public function checkLoginInfo( $inId, $inPwd )
	{
		if( $inId == false )
			return false;	// user doesn't exist
		
		$results = $this->db->select( 'pwd' )
							->from( $this->logintable )
							->where ('userid', $inId )
							->get()
							->result();
		
		if ( empty( $results ) ) 
			return false;
		else
		{
			if( $results[0]->pwd == $inPwd )
				return true;
			else
				return false; // incorrect pwd
		}
	}
	
	
	/** Add User in db
	 * @param : user nickname
	 * @param : user password (already md5)
	 * @return : false if user already exists
	 */
	public function addUser( $inUser, $inPwd )
	{
		if( $this->existingUser( $inUser ) )
			return false;
		
		$user_main_data = array(
			'nick' => $inUser 
		);
		
		$this->db->insert( $this->maintable, $user_main_data );
		
		$userid = $this->getUserId( $inUser );
		if( $userid === false )
			return false;
		
		$user_login_data = array(
			'userid' => $userid,
			'pwd' => $inPwd
		);
		
		$this->db->insert( $this->logintable, $user_login_data );
		
		return true;
	}
	
	
}

/* End of file user.php */
/* Location: ./application/models/user.php */ ?>